package com.weisy.signin.network.client;

import android.util.Log;

import com.weisy.signin.bean.MsgEvent;
import com.weisy.signin.comm.Comm;
import com.weisy.signin.network.WebConfig;
import com.weisy.signin.network.utils.StreamToolkit;
import com.weisy.signin.utils.GsonUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import kotlin.text.Charsets;

import static androidx.constraintlayout.widget.Constraints.TAG;

/**
 * @author weisy
 * @function
 * @date 2019/3/22 22:07
 */
public class HttpClient {

    private String TAG = "HttpClient";
    private WebConfig webConfig;

    public HttpClient(WebConfig webConfig) {
        this.webConfig = webConfig;
    }

    public void send(String path, String data) {
        new Thread(() -> {
            try {
                Socket socket = new Socket(webConfig.getAddress(), webConfig.getPort());
                socket.setSoTimeout(10000);
                OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8);
                StringBuilder sb = new StringBuilder();
                sb.append("GET ").append(path).append(" HTTP/1.1\r\n");
                sb.append("Host:").append(webConfig.getAddress()).append("\r\n");
                sb.append("user-agent:1601\r\n");
                sb.append("Accept-Language:zh-CN,zh;q=0.9\r\n");
                sb.append("\r\n");
                sb.append(data).append("\r\n");
                osw.write(sb.toString());
                osw.flush();
                Log.e(TAG, "客户端发出的消息=" + sb);
                InputStream ins = socket.getInputStream();
                String headLine;
                while ((headLine = StreamToolkit.readLine(ins)) != null) {
                    if ("\r\n".equals(headLine) || "\uFFFF".equals(headLine)) {
                        Log.e(TAG, "header line finish:" + headLine);
                        break;
                    }
                    Log.e(TAG, "header line=" + headLine);
                }

                String readLine;
                while ((readLine = StreamToolkit.readContent(ins)) != null) {
                    if ("\r\n".equals(readLine) || "\uFFFF".equals(readLine)) {
                        Log.d(TAG, "readLine line finish");
                        break;
                    }
                    Log.d(TAG, "readLine=" + readLine);
                    if (!"".equals(readLine.trim())) {
                        MsgEvent msg = GsonUtils.str2Bean(readLine, MsgEvent.class);
                        EventBus.getDefault().post(msg);
                        break;
                    }
                }
            } catch (Exception e) {
                if ("/".equals(path)) {
                    if (e instanceof ConnectException) {
                        MsgEvent msgEvent = new MsgEvent(Comm.SIGN_RESULT, null);
                        msgEvent.setMsg("服务器连接失败");
                        EventBus.getDefault().post(msgEvent);
                    } else if (e instanceof SocketTimeoutException) {
                        MsgEvent msgEvent = new MsgEvent(Comm.SIGN_RESULT, null);
                        msgEvent.setMsg("服务器连接超时");
                        EventBus.getDefault().post(msgEvent);
                    } else {
                        MsgEvent msgEvent = new MsgEvent(Comm.SIGN_RESULT, null);
                        msgEvent.setMsg(e.getMessage());
                        EventBus.getDefault().post(msgEvent);
                    }
                }
                e.printStackTrace();
            }
        }).start();
    }
}
